import pymysql
from dj030201.settings import *
from datetime import datetime
import random

class Customer():

    def __init__(self):
        self.serialnum = ''
        self.buy_list = []
        self.error_info = ''
        self.totalNum = 0
        self.totalPrice = 0
        self.return_money = 0
        self.receive_money = 0


    def get_serialnum(self):
        '''
        随机生成流水单号
        :return:
        '''
        dt = datetime.now()
        self.serialnum = '%04d%02d%02d%02d%02d%02d' % (dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second) + '%04d' % (random.randint(1000,9999))

    def get_product_by_barcode(self,barcode):
        '''
        通过条形码到数据库找到商品
        :param barcode:
        :return:
        '''
        mysql_db = pymysql.connect(host=DB_HOST,user=DB_USER,password=DB_PASSWORD,db=DB_NAME)
        cursor = mysql_db.cursor()
        sql = 'select * from Product where BarCode = "{}"'.format(barcode)
        try:
            cursor.execute(sql)
            product = cursor.fetchone()
            self.add_product_to_buylist(product)
        except Exception as e:
            self.error_info = '数据库出现异常，具体原因是：' + str(e)
        finally:
            mysql_db.close()

    def add_product_to_buylist(self,product):
        temp_dict = {
            'ProductId':product[0],
            'ProductName':product[2],
            'Unit':product[3],
            'UnitPrice':product[4],
            'Number':1,
            'Money':product[4],
        }
        if len(self.buy_list) == 0:
            self.buy_list.append(temp_dict)
        else:
            for index in range(len(self.buy_list)):
                if temp_dict['ProductId'] == self.buy_list[index]['ProductId']:
                    self.buy_list[index]['Number'] += 1
                    self.buy_list[index]['Money'] = self.buy_list[index]['UnitPrice'] * self.buy_list[index]['Number']
                    break
                if index == len(self.buy_list)-1:
                    self.buy_list.append(temp_dict)

    def delete_product_to_buylist(self,productId):
        for index in range(len(self.buy_list)):
            if self.buy_list[index]['ProductId'] == productId:
                self.buy_list.remove(self.buy_list[index])
                break

    def caculate_total(self):
        self.totalNum = 0
        self.totalPrice = 0
        for product in self.buy_list:
            self.totalNum += product['Number']
            self.totalPrice += product['Money']

    def calculate_return_money(self,receive_money):
        self.receive_money = float(receive_money)
        self.return_money = self.receive_money - self.totalPrice

    def keep_2(self):
        '''
        所有结果保留两位小数
        :return:
        '''
        self.totalNum = round(self.totalNum,2)
        self.totalPrice = round(self.totalPrice,2)
        self.return_money = round(self.return_money,2)
        self.receive_money = round(self.receive_money,2)

    def cashier_cancel(self):
        '''
        点击取消时，重置所有信息
        :return:
        '''
        self.serialnum = ''
        self.buy_list = []
        self.error_info = ''
        self.totalNum = 0
        self.totalPrice = 0
        self.return_money = 0
        self.receive_money = 0

    def submit(self,loginId):
        '''
        点击提交按钮后，将商品信息上传到数据库
        :return:
        '''
        mysql_db = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
        cursor = mysql_db.cursor()
        sql_list = []
        da = datetime.now()

        # 将商品货单提交到数据库
        sql = 'insert into saleslist values("{}",{},{},{},{},"{}","{}")'.format(self.serialnum,self.totalNum,self.totalPrice,self.receive_money,self.return_money,loginId,da)
        sql_list.append(sql)

        for product in self.buy_list:
            # 添加该单商品详细数据
            sql1 = 'insert into saleslistdetail (SerialNumber,ProductId,ProductName, Unit,UnitPrice,Number,Money) values("{}","{}","{}","{}",{},{},{})'.format(self.serialnum,product['ProductId'],product['ProductName'],product['Unit'],product['UnitPrice'],product['Number'],product['Money'])
            sql_list.append(sql1)

            # 更改商品库存
            sql2 = 'update product set Inventory = Inventory - {} where ProductId = "{}"'.format(product['Number'],
                                                                                                 product['ProductId'])
            sql_list.append(sql2)

        for sql in sql_list:
            try:
                cursor.execute(sql)
                mysql_db.commit()
            except Exception as e:
                mysql_db.rollback()
                print('出错的具体原因是' + str(e))

        mysql_db.close()




if __name__ == '__main__':
    cus = Customer()
    cus.get_product_by_barcode('6908512108211')
    cus.delete_product_to_buylist('6005004003001')
    print(cus.buy_list)